//index.js
import util from '../../../utils/util.js';
const http = require("../../../utils/http.js")
//获取应用实例
const app = getApp()

Component({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    WindowHeight: app.globalData.WindowHeight,

    userInfo: {},
    hasUserInfo: false,
    phone: '',
    code: '',

    time: 0,
    dialogShow: false,
    buttons: [{
        type: 'default',
        className: '',
        text: '关闭',
        value: 0
      },
      {
        type: 'primary',
        className: '',
        text: '绑定',
        value: 1
      }
    ],


    TabCur: 0,

    TabList: [{
        index: 0,
        title: '我的行程',
        num: 0
      }
      ,
      {
        index: 1,
        title: '我的印象',
        num: 0
      }
    ]
  },
  lifetimes: {
    created() {
      //在组件实例刚刚被创建时执行

    },

    attached: function() {
      // 在组件实例进入页面节点树时执行、
      let self = this
      if (app.globalData.userInfo) {
        self.saveUser(app.globalData.userInfo)
        self.getUser()
      }

    },
    detached: function() {
      // 在组件实例被从页面节点树移除时执行

    },
  },
  methods: {
    skip(e) {
      if (!app.globalData.userInfo) {
        wx.showToast({
          title: '请先登录哟',
          icon: 'none',
          duration: 1500
        })
        return;
      }

      let page = e.currentTarget.dataset.pagename
      wx.navigateTo({
        url: "/pages/mine/pages/" + page + "/" + page,
      })
    },
    saveUser(params) {
      params.openid = wx.getStorageSync("tokenId")
      http.post("/user/save", params).then(result => {
        wx.setStorageSync('userInfo', result.data.data);
        this.setData({
          userInfo: result.data.data,
          hasUserInfo: true
        })
        app.globalData.hasUserInfo = true
      })
    },
    getUser() {
      http.get("/user/getByOpenId", {
        openId: wx.getStorageSync("tokenId")
      }).then(result => {
        this.setData({
          userInfo: result.data.data,
          hasUserInfo: true
        })
        app.globalData.hasUserInfo = true
        if (this.data.hasUserInfo) {
          this.initComponent();
        }
      })
    },
    getUserInfo: function(e) {
      let _this = this;
      wx.login({
        success(res) {
          if (res.code) {
            //发起网络请求
            http.get("/user/getOpenId", {
              code: res.code
            }).then(res1 => {
              if (res1.data != null && res1.data != '') {
                let params = {
                  openid: res1.data,
                  nickname: e.detail.userInfo.nickName,
                  gender: e.detail.userInfo.gender,
                  country: e.detail.userInfo.country,
                  province: e.detail.userInfo.province,
                  city: e.detail.userInfo.city,
                  avatarUrl: e.detail.userInfo.avatarUrl,
                }
                http.post("/user/save", params).then(result => {
                  wx.setStorageSync('tokenId', res1.data);
                  app.globalData.userInfo = result.data.data
                  _this.setData({
                    userInfo: result.data.data,
                    hasUserInfo: true
                  })
                  app.globalData.hasUserInfo = true
                  _this.initComponent()
                })
              }
            })
          } else {
            console.log('登录失败！' + res.errMsg)
          }
        }
      })
    },
    tabSelect(e) {
      let edata = e.currentTarget.dataset;
      this.setData({
        TabCur: edata.tabindex,
      })
    },
    moveFinish(e) {
      this.setData({
        TabCur: e.detail.current,
      })
    },
    open: function() {
      this.setData({
        dialogShow: true
      })
    },
    tapDialogButton(e) {
      if (e.detail.item.value == 0) {
        this.setData({
          dialogShow: false,
          showOneButtonDialog: false
        })
        return;
      }
      let phone = this.data.phone;
      let code = this.data.code;
      var regNum = new RegExp('[1][3-9]{1}[0-9]{9}', 'g');
      if (!regNum.exec(phone)) {
        wx.showToast({
          title: '手机输入有误',
          icon: 'none',
          mask: true,
          duration: 1500
        })
        return;
      }
      var regCode = new RegExp('[0-9]{6}', 'g');
      if (!regCode.exec(code)) {
        wx.showToast({
          title: '验证码输入有误',
          icon: 'none',
          mask: true,
          duration: 1500
        })
        return;
      }
      let header = {
        'tokenCode': wx.getStorageSync('codeRequestId')
      }
      http.get("/user/bindPhone", {
        phone: phone,
        code: code
      }, header).then(res => {
        if (res.data.status == 200) {
          wx.removeStorage('codeRequestId')
          wx.showToast({
            title: res.data.message,
            icon: 'success',
            mask: true,
            duration: 1500
          })
          this.setData({
            phone: '',
            code: '',
            dialogShow: false,
            showOneButtonDialog: false
          })
          this.getUser();
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            mask: true,
            duration: 1500
          })
        }
      })
    },
    inputphone(event) {
      this.setData({
        phone: event.detail.value
      })
    },
    inputcode(event) {
      this.setData({
        code: event.detail.value
      })
    },
    getCode() {
      var regNum = new RegExp('[1][3-9]{1}[0-9]{9}', 'g');
      if (!regNum.exec(this.data.phone)) {
        wx.showToast({
          title: '手机格式不正确',
          icon: 'none',
          mask: true,
          duration: 1500
        })
        return;
      }
      http.get("/user/sendCode", {
        phone: this.data.phone
      }).then(res => {
        if (res.data.status == 200) {
          wx.setStorageSync("codeRequestId", res.header['tokenCode'])
          wx.showToast({
            title: res.data.message,
            icon: 'success',
            mask: true,
            duration: 1500
          })
          this.setData({
            time: 120
          })
          let codeId = setInterval(() => {
            this.setData({
              time: this.data.time - 1
            })
          }, 1000)
          setTimeout(() => {
            clearInterval(codeId)
          }, 120000)
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            mask: true,
            duration: 1500
          })
        }
      })
    },

    initComponent() {
      let self = this
      self.plan = self.selectComponent("#plan")
      self.impression = self.selectComponent("#impression")

      self.plan.initData();
      self.impression.initData();
    },
    toPlanLower() {
      if (this.plan) {
        this.plan.addData()
      }

    },
    toImpressionLower() {
      if (this.impression) {
        this.impression.addData()
      }
    }
  }
})